import datetime
from rest_framework import serializers

from django.conf import settings

from core.tools.CustomFieldsModelSerializer import DynamicFieldsModelSerializer
from apps.coffee.models import CoffeeClient, CoffeeOrder, Channel
from django.contrib.auth import get_user_model
from django.contrib.auth import authenticate

UserModel = get_user_model()


class ValidatePasswordSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    password = serializers.CharField(min_length=8, max_length=16, error_messages={
        "minx_length": "最少8位",
        "max_length": "最多16位"
    }, label="老密码", help_text="老密码")

    def validate_password(self, password):
        user = self.context["request"].user
        username = user.username
        user = authenticate(**{"username": username, "password": password})
        if user:
            return password
        else:
            raise serializers.ValidationError("原始密码不正确")

    class Meta:
        model = UserModel
        fields = ("user", "password",)


class EditPasswordSerializer(ValidatePasswordSerializer):
    new_password = serializers.CharField(min_length=8, max_length=16, error_messages={
        "minx_length": "最少8位",
        "max_length": "最多16位"
    }, label="新密码", help_text="新密码", write_only=True)

    class Meta:
        model = UserModel
        fields = ("user", "password", "new_password")

    def update(self, instance, validated_data):
        instance.set_password(validated_data["new_password"])
        instance.save()
        return instance


class CoffeeClientSerializer(DynamicFieldsModelSerializer):
    today_count = serializers.SerializerMethodField(label="今日销量", help_text="今日销量")
    month_count = serializers.SerializerMethodField(label="月销量", help_text="月销量")
    orders_count = serializers.SerializerMethodField(label="总销量", help_text="总销量")

    def get_today_count(self, instance):
        today = datetime.date.today()
        return CoffeeOrder.objects.order_count(instance.channel, start_time=today, coffee_client=instance)

    def get_month_count(self, instance):
        today = datetime.date.today()
        this_month = datetime.datetime(today.year, today.month, 1)
        return CoffeeOrder.objects.order_count(instance.channel, start_time=this_month, coffee_client=instance)

    def get_orders_count(self, instance):
        return CoffeeOrder.objects.order_count(instance.channel, coffee_client=instance)

    class Meta:
        model = CoffeeClient
        fields = ("id", "title", "today_count", "month_count", "orders_count",)


class ChannelSerializer(DynamicFieldsModelSerializer):
    month_count = serializers.SerializerMethodField(label="本月销量")
    month_sum = serializers.SerializerMethodField(label="本月销售额")

    def get_month_count(self, instance):
        today = datetime.date.today()
        start_time = datetime.date(today.year, today.month, 1)
        return CoffeeOrder.objects.order_count(instance, start_time)

    def get_month_sum(self, instance):
        today = datetime.date.today()
        start_time = datetime.date(today.year, today.month, 1)
        return CoffeeOrder.objects.order_statistics(instance, start_time)

    class Meta:
        model = Channel
        fields = ("id", "name", "img", "month_count", "month_sum",)


class StoreSerializer(DynamicFieldsModelSerializer):
    class Meta:
        model = CoffeeClient


class OrderSerializer(DynamicFieldsModelSerializer):
    # 手机号、取杯商户、取杯门店、券来源、优惠方式、消费方式、产品、价格、订单状态、交易时间
    shop_name = serializers.SerializerMethodField(label="商家名称", help_text="商家名称")
    store_name = serializers.SerializerMethodField(label="门店名称", help_text="门店名称")
    salesman = serializers.SerializerMethodField(label="销售员名称", help_text="销售员名称")
    yh = serializers.SerializerMethodField(label="优惠", help_text="优惠")
    refund_cash = serializers.SerializerMethodField(label="退款金额", help_text="退款金额")
    create_time = serializers.DateTimeField(format=settings.API_DATETIME_FORMAT, read_only=True)
    results = serializers.SerializerMethodField(label="支付结果", help_text="支付结果")
    coupon_source = serializers.SerializerMethodField(label="券来源", help_text="券来源")
    payment = serializers.SerializerMethodField(label="实收", help_text="实收")
    orderNo = serializers.SerializerMethodField(label="订单号改手机号", help_text="订单号改手机号")
    consume_type = serializers.SerializerMethodField(label="消费类型", help_text="消费类型")
    source_channel = serializers.SerializerMethodField(label="券来源(商户)", help_text="券来源(商户)")
    source_store = serializers.SerializerMethodField(label="券来源(门店)", help_text="券来源(门店)")

    def get_source_channel(self, instance):
        if instance.coupon:
            coupon_channel = instance.coupon.channel
            if coupon_channel.channel_type == 1:
                return coupon_channel.name
            elif coupon_channel.channel_type == 2:
                return coupon_channel.parent.name
            else:
                return coupon_channel.parent.parent.name
        else:
            return ""

    def get_source_store(self, instance):
        if instance.coupon:
            coupon_channel = instance.coupon.channel
            if coupon_channel.channel_type == 1:
                return ""
            elif coupon_channel.channel_type == 2:
                return coupon_channel.name
            else:
                return coupon_channel.parent.name
        else:
            return ""

    def get_consume_type(self, instance):
        if instance.coupon:
            return instance.coupon.get_sales_type_display()
        else:
            return "未知"

    def get_orderNo(self, instance):
        mobile = instance.user.mobile
        return mobile[:3] + "*" * 4 + mobile[-4:]

    def get_payment(self, instance):
        return "%.2f" % (instance.payment / 100)

    def get_coupon_source(self, instance):
        if instance.coupon:
            if instance.coupon.channel:
                return instance.coupon.channel.name
            else:
                return "未知来源"
        else:
            return "未使用券"

    def get_results(self, instance):
        return instance.get_result_display()

    def get_refund_cash(self, instance):
        if instance.result == 2:
            return instance.payment / 100
        else:
            return 0

    def get_yh(self, instance):
        if instance.coupon:
            if instance.coupon.c_type == 1:
                return "免费券A"
            elif instance.coupon.c_type == 6:
                return "免费券B"
            elif instance.coupon.c_type == 7:
                return "免费券"
            elif instance.coupon.c_type == 11:
                return "免费券C"
            else:
                # yh = "%.2f" % ((instance.cash - instance.payment) / 100)
                yh = "%.2f" % (instance.coupon.quota / 100)
                return f"优惠券-{yh}"
        else:
            yh = instance.cash - instance.payment
            if yh:
                yh = yh / 100
                yh = "%.2f" % yh
                return f"活动优惠-{yh}"
            else:
                return "没使用优惠"
    # 根据券
    # def get_shop_name(self, instance): # 全部都是发券来过滤的(谁发的券)
    #     if instance.coupon:
    #         if instance.coupon.channel.channel_type == 1:  # 商家直接返回名称
    #             return instance.coupon.channel.name
    #         elif instance.coupon.channel.channel_type == 2:  # 这个订单用的是门店券 放回上级的名称
    #             return instance.coupon.channel.parent.name
    #         else:
    #             return instance.coupon.channel.parent.parent.name  # 这个订单是用的售货员，
    #     else:
    #         return ""
    #
    # def get_store_name(self, instance):
    #     if instance.coupon:
    #         if instance.coupon.channel.channel_type == 2:  # 门店直接返回
    #             return instance.coupon.channel.name
    #         elif instance.coupon.channel.channel_type == 1:  # 商家 没有 直接是空
    #             return ""
    #         else:
    #             return instance.coupon.channel.parent.name  # 这个订单是用的售货员 返回上级
    #     else:
    #         return ""
    #
    # def get_salesman(self, instance):
    #     if instance.coupon:
    #         if instance.coupon.channel.channel_type == 3:  # 店员直接返回
    #             return instance.coupon.channel.name  # 直接返回
    #         else:
    #             return ""
    #     else:
    #         return ""

    # 根据订单取杯
    def get_shop_name(self, instance): # 全部都是发券来过滤的(谁发的券)
        if instance.coffee_client:
            if instance.coffee_client.channel.channel_type == 1:  # 商家直接返回名称
                return instance.coffee_client.channel.name
            elif instance.coffee_client.channel.channel_type == 2:  # 这个订单用的是门店券 放回上级的名称
                return instance.coffee_client.channel.parent.name
            else:
                return instance.coffee_client.channel.parent.parent.name  # 这个订单是用的售货员，
        else:
            return ""

    def get_store_name(self, instance):
        if instance.coffee_client:
            if instance.coffee_client.channel.channel_type == 2:  # 门店直接返回
                return instance.coffee_client.channel.name
            elif instance.coffee_client.channel.channel_type == 1:  # 商家 没有 直接是空
                return ""
            else:
                return instance.coffee_client.channel.parent.name  # 这个订单是用的售货员 返回上级
        else:
            return ""

    def get_salesman(self, instance):
        if instance.coffee_client:
            if instance.coffee_client.channel.channel_type == 3:  # 店员直接返回
                return instance.coffee_client.channel.name  # 直接返回
            else:
                return ""
        else:
            return ""


    class Meta:
        model = CoffeeOrder
        fields = ("orderNo", "shop_name", "store_name", "goods_name", "payment", "yh", "source_channel", "source_store",
                  "refund_cash", "create_time", "results", "coupon_source", "salesman", "consume_type")


class ChannelInfoSerializer(DynamicFieldsModelSerializer):
    month_order_count = serializers.SerializerMethodField()
    month_order_statistics = serializers.SerializerMethodField()
    count_order = serializers.SerializerMethodField()
    today_count = serializers.SerializerMethodField()

    def get_month_order_count(self, instance):
        now_day = datetime.date.today()
        month_first_day = datetime.datetime(now_day.year, now_day.month, 1)
        month_order_count = CoffeeOrder.objects.order_count(instance, month_first_day, filter_client=True)
        return month_order_count

    def get_month_order_statistics(self, instance):
        now_day = datetime.date.today()
        month_first_day = datetime.datetime(now_day.year, now_day.month, 1)
        month_order_count = CoffeeOrder.objects.order_statistics(instance, month_first_day, filter_client=True)
        return month_order_count

    def get_count_order(self, instance):
        count_order = CoffeeOrder.objects.order_count(instance, filter_client=True)
        return count_order

    def get_today_count(self, instance):
        now_day = datetime.date.today()
        today_count = CoffeeOrder.objects.order_count(instance, now_day, filter_client=True)
        return today_count

    class Meta:
        model = Channel
        fields = ("id", "key", "name", "month_order_count", "month_order_statistics", "count_order", "today_count", "img")


class ChannelSerializers(ChannelInfoSerializer):
    class Meta:
        model = Channel
        fields = ("id", "key", "name", "month_order_count", "today_count", "count_order", "url", "month_order_statistics", "img")


class UserSourceSerializers(ChannelSerializers):
    class Meta:
        model = Channel
        fields = ("id", "name",)


class UserSerializers(DynamicFieldsModelSerializer):
    channel_name = serializers.SerializerMethodField()
    channel_key = serializers.CharField(label="渠道的唯一标识", write_only=True)

    def get_channel_name(self, instance):
        if instance.coffee_channel:
            return instance.coffee_channel.name
        else:
            return ""

    def get_channel_key(self, instance):
        if instance.coffee_channel:
            return instance.coffee_channel.key
        else:
            return ""

    class Meta:
        model = UserModel
        fields = ("id", "channel_name", "password", "channel_key")

    def validate_mobile(self, mobile):
        instance = UserModel.objects.filter(mobile=mobile).first()
        if instance:
            raise serializers.ValidationError("手机号已存在")
        return mobile

    def validate(self, attrs):
        channel_key = attrs.pop("channel_key")
        instance = Channel.objects.filter(key=channel_key).first()
        attrs["username"] = channel_key
        attrs["mobile"] = channel_key
        if instance:
            attrs["coffee_channel"] = instance
        else:
            raise serializers.ValidationError("渠道不存在")
        return attrs

    def create(self, validated_data):
        print(validated_data)
        instance = super().create(validated_data)
        instance.set_password(validated_data["password"])
        instance.save()
        return instance

    def update(self, instance, validated_data):
        instance = super().update(instance, validated_data)
        instance.set_password(validated_data["password"])
        instance.save()
        return instance
